package com.lenovo.leos.letools.lenovodata;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lenovo.leos.letools.db.FileUploadEntity;
import com.lenovo.leos.letools.db.FileUploadService;
import com.lenovo.leos.letools.interaces.DownloadProgressListener;
import com.lenovo.leos.letools.utils.Constants;
import com.lenovo.leos.letools.utils.CookieStore;
import com.lenovo.leos.letools.utils.MyX509TrustManager;
import com.lenovo.leos.letools.utils.StreamTool;

public class UploadThread extends Thread {

	private String fileid;
	private String wholePath;
	private String cookie_auth;
	private String cookie_token;
	private int beginIndex;
	private DownloadProgressListener downloadProgressListener;
	private FileUploadService fileUploadService;
	private boolean flag=false;
	private UploadServer.TotalFilelenPreDir totalFilelenPreDir;//上传文件夹用到
	private static final String TAG = "UploadThread";

	//the fileLength is can be the length of file or dir,add by gaoge
	private int fileLength;
	
	public UploadThread(Context context,FileUploadEntity fue,int fileLength) {
		Log.d("UploadThread", "the fue is ============== " + fue);
		fileUploadService = new FileUploadService(context);
		if(null != fue){
			wholePath = fue.getWholePath();
			cookie_auth =  CookieStore.getCookie(context);
			cookie_token = fue.getCookie_token();
			fileid = fue.getFileid();
			beginIndex = fue.getStartIndex();//得到断点
		}
		this.fileLength = fileLength;
	}

	public void run() {
		uploadFile();
	}

	/**
	 * 上传文件
	 */
	public void uploadFile(){
		doUploadBlock();
		
		FileUploadEntity fue = fileUploadService.getFileTaskByWholePath(wholePath);
		if(fue!=null && fue.getFileState()==FileUploadEntity.upload_over){//文件全部上传结束后，执行“上传结束”
			Log.i("fileUploadEntity.getFileState()","-------------------2-----------------");
			douploadover();
		}
	}

	/**
	 * 上传一块数据
	 * 
	 * @param file
	 * @throws Exception
	 */
	DecimalFormat df = new DecimalFormat("###"); 
	public void doUploadBlock() {
		
		RandomAccessFile raf;
		
		FileUploadEntity fue = fileUploadService.getFileTaskByWholePath(wholePath);
		fileUploadService.updateIsLoading(wholePath, fileUploadService.isloading_yes);
		
		String auth = cookie_auth.substring(cookie_auth.indexOf("=") + 1);
		String token = cookie_token.substring(cookie_token.indexOf("=") + 1);
//		String url = Constants.LENOVODATA_FILE_UPLOAD + fileid + "/a=" + auth
//				+ "&t=" + token;
		String url = fue.getUploadUrl()+"/file/uploadblock/"+fileid + "/a=" + auth+ "&t=" + token;
		File uploadFile = new File(wholePath);
		  
		try {
			raf = new RandomAccessFile(uploadFile,"rwd");
			raf.seek(beginIndex);
			byte[] buf = new byte[1024];
			int length = -1;
			while ((length = raf.read(buf)) != -1 && !flag) {
				
				doPostRun(url, buf, beginIndex, ((int) beginIndex + length));
				// 更新进度条
				if(downloadProgressListener!=null) {
					
//					downloadProgressListener.onChangeDownText(value + down_and_all);
//					
//					downloadProgressListener.onDownloadSize(beginIndex);
				}
				Log.i("totalsize", "========================" + beginIndex);
				beginIndex += length;
				//文件夹用到  
				if(totalFilelenPreDir!=null) {
					//add by gaoge for show percent of upload dir
					totalFilelenPreDir.mulFileTotalLen+=length;
//					int currentUpLoadSize_dir = totalFilelenPreDir.mulFileTotalLen+length;
					double percent_dir= (double)totalFilelenPreDir.mulFileTotalLen/(double)fileLength * 100;
					String value_dir = df.format(percent_dir) + "%";
					String down_and_all_dir = " " +  transferSize(totalFilelenPreDir.mulFileTotalLen) + "/" + transferSize(fileLength);
					
					refreshDirUI(value_dir + down_and_all_dir, totalFilelenPreDir.mulFileTotalLen,totalFilelenPreDir.getDirPercent(),totalFilelenPreDir.getDirProgressBar());
					
//					totalFilelenPreDir.downloadProgressListener.onDownloadSize(currentUpLoadSize_dir);
//					totalFilelenPreDir.downloadProgressListener.onChangeDownText(value_dir + down_and_all_dir);
				}
				//更新断点
				fileUploadService.updateBlockPosition(wholePath, beginIndex);
			}
			raf.close();
			if(beginIndex == uploadFile.length()){//文件上传完成，修改该文件对应的状态为已上传完成
				fileUploadService.updateFileState(wholePath,FileUploadEntity.upload_over);
				Log.i("fileUploadEntity.getFileState()","-------------------3-----------------");
			}else{
				Log.i("pause","-------------------pause-----------------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			fileUploadService.updateIsLoading(wholePath, fileUploadService.isloading_no);
		}
	}
	public void doPostRun(String url, byte[] buf, int begin, int end) {
		Log.i(TAG, "--------------begin="+begin+"==end="+end);
		MyX509TrustManager.allowAllSSL();
		HttpURLConnection urlCon;
		OutputStream out;
		try {
			urlCon = (HttpURLConnection) (new URL(url)).openConnection();
			urlCon.setRequestMethod("POST");
			urlCon.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			urlCon.setRequestProperty("Range","bytes="+begin+"-"+end);
			urlCon.setDoInput(true);
			urlCon.setDoOutput(true);
			out = urlCon.getOutputStream();
			out.write(buf, 0, end - begin);
			out.flush();
			out.close();
			InputStream in = urlCon.getInputStream();
			in.close();
//			double percent = (double)beginIndex/(double)fileLength * 100;
			//modify by gaoge because when upload little file ,the percent cann't be 100%,such as only 96%
			double percent = (double)end/(double)fileLength * 100;
			String value = df.format(percent) + "%";
			String down_and_all = " " +  transferSize(end) + "/" + transferSize(fileLength);
			
			//add by gaoge 2011-04-26
			Log.d(TAG,"####################### beginIndex is: " + beginIndex + ",fileLength is: " + fileLength);
			refreshUI(value + down_and_all, end);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 完整文件上传完成
	 * 
	 * @throws Exception
	 */
	public void douploadover() {
		HttpURLConnection conn;
		URL url;
		InputStream in;
		String auth = cookie_auth.substring(cookie_auth.indexOf("=") + 1);
		String token = cookie_token.substring(cookie_token.indexOf("=") + 1);

		String localFileid = fileid.substring(0,fileid.indexOf("."));
		try {
			url = new URL(Constants.LENOVODATA_FILE_UPLOADOVER+localFileid+"/a="+auth+"&t="+token);
			Log.i("douploadover","================"+url.toString());
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("method","GET");
			conn.setRequestProperty("Cookie",cookie_auth);
			conn.connect();
			in = conn.getInputStream();
			Log.i("douploadover","================"+conn.getResponseCode());

			byte[] buf = StreamTool.getByteData(in);
			String retVal = new String(buf, "utf-8");
			in.close();
			conn.disconnect();
			Log.i("douploadover","======douploadover=========="+retVal);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void setDownloadProgressListener(
			DownloadProgressListener downloadProgressListener) {
		this.downloadProgressListener = downloadProgressListener;
	}
	public void setFlag(boolean flag){
		this.flag=flag;
	}

	public void setTotalFilelenPreDir(UploadServer.TotalFilelenPreDir totalFilelenPreDir) {
		this.totalFilelenPreDir = totalFilelenPreDir;
	}
	
	 private String transferSize(long lSize) {
         String size;
         int iPoint;
         if (lSize < 1024) {
                 size = lSize + "B";
         } else if (lSize < 1024 * 1024) {
                 size = String.valueOf(lSize / 1024.0);
                 iPoint = size.indexOf(".");
                 size = size.substring(0, iPoint + 2) + "K";
         } else if (lSize < 1024 * 1024 * 1024) {
                 size = String.valueOf(lSize / 1024.0 / 1024);
                 iPoint = size.indexOf(".");
                 size = size.substring(0, iPoint + 2) + "M";
         } else if (lSize < 1024L * 1024L * 1024L * 1024L) {
                 // Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_G="+lSize);
                 size = String.valueOf(lSize / 1024.0 / 1024 / 1024);
                 iPoint = size.indexOf(".");
                 size = size.substring(0, iPoint + 2) + "G";
         } else if (lSize < 1024L * 1024L * 1024L * 1024L * 1024L) {
                 // Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_T="+lSize);
                 size = String.valueOf(lSize / 1024.0 / 1024 / 1024 / 1024);
                 iPoint = size.indexOf(".");
                 size = size.substring(0, iPoint + 2) + "T";
         } else {
                 // Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_Unknown="+lSize);
                 size = "unknown";
         }

         return size;
 }
	 
	//add by gaoge 2011-04-25 
		private TextView tv_percent;
		private ProgressBar mProgressBar;
		
		public void setTv_percent(TextView tvPercent) {
			this.tv_percent = tvPercent;
		}

		public void setmProgressBar(ProgressBar mProgressBar) {
			this.mProgressBar = mProgressBar;
		}
		
		public static final int CHANGE_PERCENT = 1;
		public static final int CHANGE_PERCENT_DIR = 2;
		 
		 private TextView tv_tmp_dir;
		 
		 private Handler mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if(CHANGE_PERCENT == msg.what){
					if(null != tv_percent){
						tv_percent.setText((String)msg.obj);
					}
				}
				else if(CHANGE_PERCENT_DIR == msg.what){
					tv_tmp_dir.setText((String)msg.obj);
				}
			}
		 };
		 
		 private void refreshDirUI(String tv_percent_val_dir,int progrossBarSize,TextView tv_dir,ProgressBar bar_dir ){
//			 for(int i=0;i<5;i++){
//				 Log.d("UploadThread","######################  refreshDirUI,progrossBarSize is: " + progrossBarSize
//						 + ",tv_percent_val_dir is: " + tv_percent_val_dir);
//			 }
			 tv_tmp_dir = tv_dir;
			 bar_dir.setProgress(progrossBarSize);
			 msg = mHandler.obtainMessage(CHANGE_PERCENT_DIR, tv_percent_val_dir);
			 mHandler.sendMessage(msg);
		 }
		 
		 Message msg;
		 private void refreshUI(String tv_percent_val,int progrossBarSize){
//			 for(int i=0;i<5;i++){
//				 Log.d("UploadThread","######################### refreshUI ,null != mProgressBar " + (null != mProgressBar) );
//			 }
			 if(null != mProgressBar){
				 mProgressBar.setProgress(progrossBarSize);
				 msg = mHandler.obtainMessage(CHANGE_PERCENT, tv_percent_val);
				 mHandler.sendMessage(msg);
			 }
		 }
}
